package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;

import com.heima.utils.thread.AppUserThreadLocal;
import com.heima.utils.thread.WmUserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * es文章分页检索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        // 校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 将查询关键词保存
        ApUser user = AppUserThreadLocal.getUser();
        if (user != null) {
            // 异步调用数据保存
            apUserSearchService.insert(dto.getSearchWords(), user.getId());
        }

        // 分页参数(从第几个开始)
        int fromIndex = dto.getFromIndex();

        // 构造查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");

        // 关键词和最小时间匹配
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"))
                .filter(QueryBuilders.rangeQuery("publish_time").lte(dto.getMinBehotTime()));

        searchRequest.source().query(boolQuery);

        // 排序
        searchRequest.source().sort("publish_time", SortOrder.DESC);

        // 分页匹配
        searchRequest.source()
                .from(fromIndex)
                .size(dto.getPageSize());

        // 高亮
        searchRequest.source().highlighter(SearchSourceBuilder.highlight()
                .field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));

        // 发送查询请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析查询结果
        List<Map> list = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if (hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0) {
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title", title);
            } else {
                //原始标题
                map.put("h_title", map.get("title"));
            }
            list.add(map);
        }


        return ResponseResult.okResult(list);
    }

}